package com.weixin.mw.itcar.action;

import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.weixin.mw.itcar.common.StringUtil;

/**
 * Servlet implementation class HelloWeChat
 */
public class Myservlet extends HttpServlet {
	private static final long serialVersionUID = -8797255288657251723L;
	public static final String Token = "mengwei";
	private static final Log logger = LogFactory.getLog(Myservlet.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Myservlet() {
		super();
	}

	/**
	 * @see HttpServlet#
(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			InputStream is = request.getInputStream();
			// 取HTTP请求流长度
			int size = request.getContentLength();
			// 用于缓存每次读取的数据
			byte[] buffer = new byte[size];
			// 用于存放结果的数组
			byte[] xmldataByte = new byte[size];
			int count = 0;
			int rbyte = 0;
			// 循环读取
			while (count < size) { 
				// 每次实际读取长度存于rbyte中
				rbyte = is.read(buffer); 
				for(int i=0;i<rbyte;i++) {
					xmldataByte[count + i] = buffer[i];
				}
				count += rbyte;
			}
			is.close();
		  System.out.println("===="+this.getClass().getResource("/").getPath().substring(1));
			String requestStr = new String(xmldataByte, "UTF-8");
			Document doc = DocumentHelper.parseText(requestStr);
			Element rootElt = doc.getRootElement();
			String content = rootElt.elementText("Content");
			String toUserName = rootElt.elementText("ToUserName");
			String fromUserName = rootElt.elementText("FromUserName");
			//得到所有的有用数据
			System.out.println(content+ ":" + toUserName + ":" + fromUserName);
			//文本消息
			if (! StringUtil.isBlank(content) && "text".equals(content)) {
				String responseStr = "<?xml version='1.0' encoding='utf-8'?><xml>";
				responseStr += "<ToUserName><![CDATA[" + fromUserName
				+ "]]></ToUserName>";
				responseStr += "<FromUserName><![CDATA[" + toUserName
				+ "]]></FromUserName>";
				responseStr += "<CreateTime>" + System.currentTimeMillis()
				+ "</CreateTime>";
				responseStr += "<MsgType><![CDATA[text]]></MsgType>";
				responseStr += "<Content>输入text信息，这个是回复</Content>";
				responseStr += "<FuncFlag>0</FuncFlag>";
				responseStr += "</xml>";
				response.getWriter().write(responseStr);
			}
			//图文消息
			else if (! StringUtil.isBlank(content) && "news".equals(content)) {
				String responseStr = "<xml>";
				responseStr += "<ToUserName><![CDATA[" + fromUserName
				+ "]]></ToUserName>";
				responseStr += "<FromUserName><![CDATA[" + toUserName
				+ "]]></FromUserName>";
				responseStr += "<CreateTime>" + System.currentTimeMillis()
				+ "</CreateTime>";
				responseStr += "<MsgType><![CDATA[news]]></MsgType>";
				responseStr += "<Content><![CDATA[]]></Content>";

				responseStr += "<ArticleCount>2</ArticleCount>";

				responseStr += "<Articles>";
				responseStr += "<item>";
				responseStr += "<Title><![CDATA[图文消息——红色石头]]></Title>";
				responseStr += "<Discription><![CDATA[图文消息正文——红色石头]]></Discription>";
				responseStr += "<PicUrl><![CDATA[http://redstones.sinaapp.com/res/images/redstones_wx_258.jpg]]></PicUrl>";
				responseStr += "<Url><![CDATA[http://redstones.sinaapp.com/]]></Url>";
				responseStr += "</item>";

				responseStr += "<item>";
				responseStr += "<Title><![CDATA[图文消息——红色石头]]></Title>";
				responseStr += "<Discription><![CDATA[图文消息正文——红色石头]]></Discription>";
				responseStr += "<PicUrl><![CDATA[http://redstones.sinaapp.com/res/images/redstones_wx_258.jpg]]></PicUrl>";
				responseStr += "<Url><![CDATA[http://redstones.sinaapp.com/]]></Url>";
				responseStr += "</item>";

				responseStr += "</Articles>";
				responseStr += "<FuncFlag>1</FuncFlag>";
				responseStr += "</xml>";
				response.getWriter().write(responseStr);
			}
			//不能识别
			else {
				String responseStr = "<xml>";
				responseStr += "<ToUserName><![CDATA[" + fromUserName
				+ "]]></ToUserName>";
				responseStr += "<FromUserName><![CDATA[" + toUserName
				+ "]]></FromUserName>";
				responseStr += "<CreateTime>" + System.currentTimeMillis()
				+ "</CreateTime>";
				responseStr += "<MsgType><![CDATA[text]]></MsgType>";
				responseStr += "<Content>输入text或者news返回相应类型的消息</Content>";
				responseStr += "<FuncFlag>0</FuncFlag>";
				responseStr += "</xml>";
				response.getWriter().write(responseStr);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}